<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vue2.X响应式原理</title>
</head>

<body>
  <script>
    // 模拟Vue中的data选项
    let data = {
      name: 'Tom',
      age: 18,
    }
    // 实现一个响应式函数
    function defineProperty(obj, key, val) {
       //如果某对象的属性也是一个对象，递归进入该对象，进行监听
      if(typeof val === 'object'){
        Observer(val)
      }
      Object.defineProperty(obj, key, {
        get() {
          console.log(`访问了${key}属性`)
          return val
        },
        set(newVal) {
          console.log(`${key}属性被修改为${newVal}了`)
          val = newVal
        }
      })
    }
    // 实现一个遍历函数Observer
    function Observer(obj) {
      Object.keys(obj).forEach((key) => {
        defineProperty(obj, key, obj[key])
      })
    }
    Observer(data)
    data.name = 'Lily'
    console.log(data.name);
    data.age = 20
    console.log(data.age);
  </script>
</body>

</html>